/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taskmanager2ndedition.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import taskmanager2ndedition.Connection;

/**
 *
 * @author denaas
 */
public class ClientConnection implements Connection {

    private Socket socket;    
    private ObjectInputStream in;    
    private ObjectOutputStream out;
    private int timeout = 300000;
            
    public ClientConnection(String host, int port) throws IOException {
        socket = new Socket(host, port);
        createStreams();
    }
    
    public ClientConnection(byte [] addr, int port) throws UnknownHostException, IOException {
        InetAddress address = Inet4Address.getByAddress(addr);
        socket = new Socket(address, port);
        createStreams();
    }
    
    private void createStreams() throws IOException {        
        out = new ObjectOutputStream(socket.getOutputStream()); 
        in = new ObjectInputStream(socket.getInputStream());
    }

    public synchronized String send(String message) {
        try {
            out.writeUTF(message);
            out.flush();
            return receive();
        } catch (Exception ex) {
            return null;
        }
    }
    
    private synchronized String receive() throws IOException {
        int time = 0;
        while (in.available() == 0){
            try {
                Thread.sleep(100);
                time += 100;
                if (time >= timeout)
                    return null;
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
                    
        return in.readUTF();
    }
}
